#include "../server.hpp"
#include <regex>
#include <fstream>

std::unordered_map<int, std::string> status_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

class Util
{
public:
    static size_t Split(const string& src, const string& sep, vector<string>* res)
    {
        size_t start = 0;
        while(start < src.size())
        {
            size_t pos = src.find(sep,start);
            if(pos == string::npos)
            {
                res->push_back(src.substr(start));
                break;
            }
            else
            {
                if(pos - start > 0)     //不要空串
                {
                    res->push_back(src.substr(start, pos - start));
                }
                start = pos + sep.size(); 
            }
        }

        return res->size();
    }
    
    static bool ReadFile(const string& filename, Buffer* buffer)
    {
        std::ifstream ifs(filename.c_str(), std::ios::binary);
        if(!ifs.is_open())
        {
            ERR_LOG("open failed: %s", strerror(errno));
            return false;
        }

        //可以循环读一个固定大小直到EOF，也可先获取文件大小然后直接开辟对应大小的空间
        ifs.seekg(0,ifs.end);
        int size = ifs.tellg();
        ifs.seekg(0,ifs.beg);

        buffer->SetBufferSize(size);
        ifs.read(buffer->GetWritePosition(), size); 
        buffer->MoveWriteIndex(size);       //直接移动写指针位置，保证比较符合Buffer设计情况下，正确计算大小
        if(!ifs.good())
        {
            ERR_LOG("read failed: %s", strerror(errno));
            ifs.close();
            return false;
        }

        ifs.close(); 
        return true;
    }
    static bool ReadFile(const string& filename, string* buffer)
    {
        std::ifstream ifs(filename.c_str(), std::ios::binary);
        if(!ifs.is_open())
        {
            ERR_LOG("open failed: %s", strerror(errno));
            return false;
        }

        //可以循环读一个固定大小直到EOF，也可先获取文件大小然后直接开辟对应大小的空间
        ifs.seekg(0,ifs.end);
        int size = ifs.tellg();
        ifs.seekg(0,ifs.beg);

        buffer->resize(size);       //读文件操作一定要提前开空间！
        ifs.read(&((*buffer)[0]), size);

        if(!ifs.good())
        {
            ERR_LOG("read failed: %s", strerror(errno));
            ifs.close();
            return false;
        }

        ifs.close(); 
        return true;
    }

    static bool WriteFile(const string& filename, Buffer* buffer)
    {
        std::ofstream ofs (filename, std::ios::trunc);
        if(!ofs.is_open())
        {
            ERR_LOG("open failed: %s", strerror(errno));
            return false;            
        }

        int size = buffer->GetReadableSize();
        ofs.write(buffer->GetReadPosition(), size);
        buffer->MoveReadIndex(size);       //同理

        ofs.close();
        return true;
    }
    static bool WriteFile(const string& filename, string* buffer)
    {
        std::ofstream ofs (filename, std::ios::trunc);
        if(!ofs.is_open())
        {
            ERR_LOG("open failed: %s", strerror(errno));
            return false;            
        }

        ofs.write(buffer->c_str(), buffer->size());

        ofs.close();
        return true;
    }

    static string UrlEncode(const string& url, bool is_plus_to_space)
    {
        string res;
        for(auto c : url)
        {
            //1.数字和字母不编码    2.四个特殊字符不编码
            if(isalnum(c) || (c == '.' || c == '-' || c == '_' || c == '~'))
            {
                res += c;
            }  
            else    //3.+号的两种编码方式
            {
                if(c == '+' && is_plus_to_space)
                {
                    res += ' ';
                }
                else
                {
                    char tmp[4] = {0};      //为什么是4? --> 需要预留一个位给'/0'
                    snprintf(tmp,4,"%%%02X",c);
                    res += tmp;
                }
            }    
        }
        
        return res;
    }

    static int DeHex(char c)
    {
        if(c >= '1' && c <= '9')
        {
            return c - '0';
        }
        else if(tolower(c) >= 'a' && tolower(c) <= 'f')
        {
            return tolower(c) - 'a' + 10;
        }
    }
    static string UrlDecode(const string& url, bool is_plus_to_space)
    {
        string res;
        for(int i = 0; i < url.size(); i++)
        {
            if(url[i] == '%' && i+2 < url.size())
            {
                char c1 = url[i+1];
                char c2 = url[i+2];
                char tmp = Util::DeHex(c1) * 16 + Util::DeHex(c2);

                cout << (int)tmp << endl;
                if(is_plus_to_space && tmp == '+')
                {
                    res += ' ';
                }
                else
                {
                    res += tmp;
                }
                i+=2;
            }
            else
            {
                res += url[i];
            }
        }

        return res;
    }


    static string StatusDesc(int status)   
    {
        if(status_msg.count(status) == 0)
        {
            return "Unknown";
        }
        return status_msg[status];
    }

    static string ExtractMime(const string& filename)
    {
        size_t pos = filename.find_last_of('.');
        if(pos == string::npos)     //注意错误处理
        {
            return "application/octet-stream";
        }

        string s = filename.substr(pos);
        if(mime_msg.count(s) == 0)
        {
            return "application/octet-stream";
        }
        return mime_msg[s];
    }

    static bool IsDirectory(const string& filename)
    {
        struct stat buf;
        int ret = stat(filename.c_str(), &buf);
        if(ret < 0)
        {
            ERR_LOG("stat failed: %s", strerror(errno));
            return false;
        }

        return S_ISDIR(buf.st_mode);
    }

    static bool IsRegular(const string& filename)
    {
        struct stat buf;
        int ret = stat(filename.c_str(), &buf);
        if(ret < 0)
        {
            return false;
        }

        return S_ISREG(buf.st_mode);
    }

    static bool IsValidPath(const string& path)
    {
        vector<string> res;
        size_t n = Util::Split(path, "/", &res);
        int level = 0;
        for(int i = 0; i < n; i++)
        {
            if(res[i] == "..")
            {
                if(--level < 0)
                {
                    return false;
                }
            }
            else 
            {
                //if(res[i].find(".") == string::npos)  这倒不用，具体资源一定在路径最后
                level++;
            }
        }

        return true;
    }
};

class HttpRequest
{
public:
    string _method;
    string _path;
    string _version;
    string _body;
    std::smatch _matches;

    std::unordered_map<string, string> _headers;
    std::unordered_map<string, string> _params;

public:
    HttpRequest():_version("HTTP/1.1"), _body("")  {}

    void SetHeader(const string& key, const string& value)  {_headers[key] = value;}

    bool HasHeader(const string& key)   {return _headers.count(key);}

    string GetHeader(const string& key)
    {
        if(HasHeader(key))
        {
            return _headers[key];
        }

        return "";
    }

    void SetParam(const string& key, const string& value)   {_params[key] = value;}

    bool HasParam(const string& key)    {return _params.count(key);}

    string GetParam(const string& key)
    {
        if(HasParam(key))
        {
            return _params[key];
        }

        return "";
    }  

    size_t GetContentLength()
    {
        if(!HasHeader("Content-Length"))        //fix bug: HasParam --> HasHeader
        {
            return 0;
        }
        return stol(_headers["Content-Length"]);
    }

    bool IsClose(){return !((HasHeader("Connection")) && (GetHeader("Connection") == "keep-alive"));}

    void Reset()
    {
        _method.clear();    _path.clear();
        _version = "HTTP/1.1";   _body.clear();
        std::smatch matches;    matches.swap(_matches);
        _headers.clear();   _params.clear();

    }
};

class HttpResponse
{
public:
    int _status;
    string _body;
    bool _redirect_flag;
    string _redirect_url;

    std::unordered_map<string, string> _headers;
public:
    HttpResponse(int status = 200):_status(status), _redirect_flag(false) {}
    void SetHeader(const string& key, const string& value)  {_headers[key] = value;}
    bool HasHeader(const string& key)   {return _headers.count(key);}

    string GetHeader(const string& key)
    {
        if(HasHeader(key))
        {
            return _headers[key];
        }

        return "";
    }

    void SetContent(const string& content, const string& type)  
    {
        _body = content;
        SetHeader("Content-Type", type);        //记得进行相关请求头字段的设置
    }

    void SetRedirect(const string& url, int status = 302)
    {
        _status = status;
        _redirect_flag = true;
        _redirect_url = url;
    }

    bool IsClose(){return (HasHeader("Connection") && GetHeader("Connection") == "keep-alive");}

    void Reset()
    {
        _status = 0;    _body.clear();
        _redirect_flag = false; _redirect_url.clear();
        _headers.clear();
    }
};

typedef enum{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER,
}HttpRecvStatus;

class HttpContext
{
private:
    int _resp_status;
    HttpRecvStatus _recv_status;
    HttpRequest _request;

private:
#define MAX_LENGTH 8192
    bool RecvHttpLine(Buffer* buffer)
    {
        DBG_LOG("RecvHttpLine");
        if(_recv_status != RECV_HTTP_LINE)
        {
            return false;
        }

        string line = buffer->GetLine();

        //1.没找到\r\n  此时应该对应两种情况
        if(line == "")
        {
            //1.1   数据太多
            if(buffer->GetReadableSize() > MAX_LENGTH)
            {
                _resp_status = 414;
                _recv_status = RECV_HTTP_ERROR;
                return false;
            }

            //1.2   数据不足
            return true;
        }
        //2.找到了\r\n但数据太长
        else if(line.size() > MAX_LENGTH)
        {
            _resp_status = 414;
            _recv_status = RECV_HTTP_ERROR;
            return false;
        }

        bool ret = ParseHttpLine(line);       //不能直接return，因为还有设置处理状态
        if(ret == false)    return false;

        _recv_status = RECV_HTTP_HEAD;
        DBG_LOG("RecvHttpLine done");
        return true;
    }

    bool ParseHttpLine(const string& line)
    {
        std::smatch sm;
        // std::regex e ("(GET|HEAD|POST|PUT|DELETE).*" "([^?]+).*"     ---bug
        // "(?:\\?(.*?))? .*" "(HTTP/1\\.[0|1])(?:\n|\r\n)", std::regex::icase);   //std::regex::icase 忽略大小写
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        bool ret = std::regex_match(line, sm, e);

        if(sm.size() != 5 || ret == false)
        {
            _resp_status = 400;     //Bad Request
            _recv_status = RECV_HTTP_ERROR;
            return false;
        }

        //填充request字段 细节：请求方法在输入时可能是小写的；为方便处理，统一转换为大写
        _request._method = sm[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        _request._path = Util::UrlDecode(sm[2], false);     //fix bug: 查询

        _request._version = sm[4];

        //查询字符串有可能有许多键值对
        vector<string> params;
        Util::Split(sm[3], "&", &params);

        for(int i = 0 ; i < params.size(); i++)
        {
            size_t pos = params[i].find('=');
            if(pos == string::npos)
            {
                _resp_status = 400;     //Bad Request
                _recv_status = RECV_HTTP_ERROR;
                return false;
            }

            _request.SetParam(Util::UrlDecode(params[i].substr(0,pos),true)
            ,Util::UrlDecode(params[i].substr(pos+1),true));
        }

        //cout<< "debug: " << _request._method +" " + _request._path + " " + _request._version << endl;
        return true;
    }

    bool RecvHttpHeader(Buffer* buffer)
    {
        DBG_LOG("RecvHttpHeader");
        if(_recv_status != RECV_HTTP_HEAD)
        {
            return false;
        }

        while (1)
        {
            string line = buffer->GetLine();

            if(line == "")
            {
                //1.1   数据太多
                if(buffer->GetReadableSize() > MAX_LENGTH)
                {
                    _resp_status = 414;
                    _recv_status = RECV_HTTP_ERROR;
                    return false;
                }

                //1.2   数据不足
                return true;
            }
            else if(line.size() > MAX_LENGTH)
            {
                _resp_status = 414;
                _recv_status = RECV_HTTP_ERROR;
                return false;
            }

            if(line == "\r\n" || line == "\n")      //fix: / --> \ !!!
            {
                break;
            }

            bool ret = ParseHttpHeader(line);     //读取一行处理一行
            if(ret == false)
            {
                _resp_status = 400;
                _recv_status = RECV_HTTP_ERROR;
                return false;
            }
        }

        _recv_status = RECV_HTTP_BODY;
        DBG_LOG("RecvHttpHeader done");
        return true;
    }

    bool ParseHttpHeader(string& line)
    {
        //为了后面统一响应协议格式的组织，也符合键值对关系，先将末尾\r\n去除
        if (line.back() == '\n') line.pop_back();
        if (line.back() == '\r') line.pop_back();
        
        size_t pos = line.find(':');    
        if(pos == string::npos)
        {
            return false;
        }

        _request.SetHeader(line.substr(0,pos), line.substr(pos+2));     //细节：请求头字段格式中还有一个空格，所以+2;
        return true;
    }

    bool RecvHttpBody(Buffer* buffer)
    {
        DBG_LOG("RecvHttpBody");
        if(_recv_status != RECV_HTTP_BODY)
        {
            return false;
        }

        if(_request.GetContentLength() == 0)
        {
            _recv_status = RECV_HTTP_OVER;
            return true;
        }
        size_t real_len = _request.GetContentLength() - _request._body.size();

        // if(real_len > buffer->GetReadableSize())        //缓冲区数据不足，需继续读取
        // {
        //     return false;    fix bug: 但要先把已有的数据取出来
        // }

        //缓冲区中数据，包含了当前请求的所有正文，则取出所需的数据
        if(real_len <= buffer->GetReadableSize())      //注意还有个等于
        {
            //_request._body += string(buffer->GetReadPosition(), real_len);    ?x
            _request._body.append(buffer->GetReadPosition(), real_len);
            buffer->MoveReadIndex(real_len);
            _recv_status = RECV_HTTP_OVER;
            return true;
        }

        //缓冲区中数据，无法满足当前正文的需要，先取出数据，然后等待新数据到来，注意此时不能改变接收状态
        _request._body.append(buffer->GetReadPosition(), buffer->GetReadableSize());
        buffer->MoveReadIndex(buffer->GetReadableSize());
        
        DBG_LOG("RecvHttpBody done");
    }

public:
    HttpContext() :_resp_status(200) , _recv_status(RECV_HTTP_LINE){}
    int GetRespStatus() {return _resp_status;}
    HttpRecvStatus GetRecvStatus() {return _recv_status;}

    HttpRequest& GetRequest()   {return _request;}

    void Reset()
    {
        _resp_status = 200;
        _recv_status = RECV_HTTP_LINE;
        _request.Reset();
    }

    void HandleHttpRequest(Buffer* buffer)
    {
        DBG_LOG("HandleHttpRequest");
        
        switch(_recv_status)
        {
            case RECV_HTTP_LINE:
                RecvHttpLine(buffer);
            case RECV_HTTP_HEAD:
                RecvHttpHeader(buffer);
            case RECV_HTTP_BODY:
                RecvHttpBody(buffer);
        }
    }

};

class HttpServer
{    
private:
    using Handler = std::function<void(HttpRequest&, HttpResponse*)>;
    //using Handlers = std::unordered_map<std::regex, Handler>;     unordered_map的判等对正则表达式支持得不太好
    using Handlers = std::vector<std::pair<std::regex, Handler>>;

    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;

    string _basedir;
    TcpServer _server;

private:
    //协议设置
    void OnConnected(const PtrConnection& pc)
    {
        // if(!pc->IsConnected())
        // {
        //     return;
        // }
        
        pc->SetContext(HttpContext());
        ERR_LOG("NEW CONNECTION %p", pc.get());
    }
    
    //核心 --> 绑给TcpServer的，连接建立成功后，由“那边底层”，把缓冲区的数据带上来
    void OnMessage(const PtrConnection& pc, Buffer* buffer)
    {
        // if(!pc->IsConnected())          //对的原因！！！
        // {
        //     buffer->DataClean();
        //     return;
        // }

        while(buffer->GetReadableSize() > 0) 
        {
            //1. 将数据从缓冲区中取出构建request
            //?:内存泄露问题 --> 不会，因为每次获取的都是Connection中已经设置好的context，其生命周期随连接；而不是每次循环都new一个HttpContext出来
            HttpContext* context = pc->GetContext()->Get<HttpContext>();    
            context->HandleHttpRequest(buffer);

            //用context的resp状态码来初始化HttpResponse对象 
            //--> 由于HttpContext是对HttpRequest的处理，故请求的情况和响应就挂钩了！！！
            HttpResponse rsp(context->GetRespStatus());
            HttpRequest& req = context->GetRequest();
            if(rsp._status >= 400)
            {
                ErrorHandler(&rsp);
                WriteResponse(pc, req, &rsp);   //req还没构建好怎么办? --> req一定是构建好了的，但只是不一定是正确的请求！！！
                context->Reset();
                buffer->DataClean();
                pc->Shutdown();
                return;
            }

            //细节：需要等当前请求接收完整后才进行下一步,否则返回底层继续接收
            if(context->GetRecvStatus() != RECV_HTTP_OVER)
            {
                return;
            }

            //2. 直接进行路由，由路由函数根据request判断是哪种请求，并进行对应处理
            Route(req, &rsp);

            //3. 由WriteResponse函数集中组织response并进行发送（其他各处理中只对response的状态码进行设置）
            WriteResponse(pc,req,&rsp);
        
            //4. 细节：发送后需要重置上下文，避免对下次处理造成影响 --> 怎么造成的?
            context->Reset();

            //5. 根据连接长短的设置来判断是否关闭连接
            if(req.IsClose())
            {
                pc->Shutdown();
            }            
        }

    }

    void ErrorHandler(HttpResponse* rsp)
    {
        //1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp->_status);
        body += " ";
        body += Util::StatusDesc(rsp->_status);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        //2. 将页面数据，当作响应正文，放入rsp中
        rsp->SetContent(body, "text/html");
    }

    //先判断是否请求的是静态资源，如果是，则还要保证静态资源的正确请求
    bool IsFileHandler(HttpRequest& req)
    {
        if(req._method != "GET" && req._method != "HEAD")
        {
            return false;
        }

        if(_basedir.empty())    return false;

        if(!Util::IsValidPath(req._path))   return false;

        //特殊情况：如果请求的是根目录,自动拼接该根目录下的首页文件
        //当然 请求本身可能就不是动态资源的请求，如：GET /users/{userId}（获取用户信息）

        string req_path = _basedir + req._path;     //若请求是静态资源且存在，需要加上完整的路径，后面函数判断才能为真
        if(req._path.back() == '/')
        {
            req_path += "index.html";
        }

        //若请求的资源不存在，如何判断? --> 封装的IsRegular接口“天然”可以判断
        if(!Util::IsRegular(req_path))
        {
            return false;
        }

        return true;
    }

    void FileHandler(HttpRequest& req, HttpResponse* rsp) 
    {
        //还是避免直接修改request中的path
        string req_path = _basedir + req._path;
        if(req._path.back() == '/')
        {
            req_path += "index.html";
        }

        int ret = Util::ReadFile(req_path, &rsp->_body);      //可以直接写入rsp的body中，不需要buffer了

        if(ret == false)    return;
        rsp->SetHeader("Content-Type", Util::ExtractMime(req_path));
    }

    void Dispatcher(HttpRequest& req, HttpResponse* rsp, Handlers handlers)
    {
        for(auto& handler : handlers)
        {
            if(std::regex_match(req._path, req._matches, handler.first))
            {
                handler.second(req, rsp);
                return;
            }
        }

        rsp->_status = 404;
    }

    void Route(HttpRequest& req, HttpResponse* rsp)
    {
        if(IsFileHandler(req))
        {
            return FileHandler(req, rsp);
        }     
        
        if(req._method == "GET" || req._method == "HEAD") Dispatcher(req, rsp, _get_route);
        else if(req._method == "POST") Dispatcher(req, rsp, _post_route);
        else if(req._method == "PUT") Dispatcher(req, rsp, _put_route);
        else if(req._method == "DELETE") Dispatcher(req, rsp, _delete_route);
        else {rsp->_status = 405;}
    }

    void WriteResponse(const PtrConnection& pc, HttpRequest& req, HttpResponse* rsp)
    {
        DBG_LOG("WriteResponse");
        //设置字段时相关字段需先判断是否存在
        rsp->SetHeader("Connection", req.GetHeader("Connection"));
        if(!rsp->HasHeader("Content-Length") && !rsp->_body.empty())        //没有才设置，若在其他函数中设置过了则无需设置
        {
            rsp->SetHeader("Content-Length", std::to_string(rsp->_body.size()));
        }
        if(!rsp->HasHeader("Content-Type") && !rsp->_body.empty())
        {
            rsp->SetHeader("Content-Type", "application/octet-stream");
        }
        if(rsp->_redirect_flag)
        {
            rsp->SetHeader("Location", rsp->_redirect_url);
        }

        //fix bug: 直接输出body无内容，但输出body.c_str()就正确 --> ReadFile的时候是直接往string的首元素的地址写，没有经过string内部
        //故string的size等属性并没有更新！！！size还是0！！！而输出和+=等操作要参考string的size！！！
        //故最后context中没内容！！！
        //解决：修改ReadFile 或 +=body.c_str() 或 用string流进行协议格式组合（√）

        //fix bug: 访问首页时内容解析不出来 --> 在原来的ParseHttpHeader中，在存储类型对应的值时没有将末尾的\r\n去掉，而最后在协议组织时
        //又多加上了一个\r\n，导致浏览器接收后解析错误，故ParseHttpHeader中在存储值时先把末尾的\r\n去掉！！！
        std::stringstream ss;
        ss << req._version << " " << std::to_string(rsp->_status) << " " << Util::StatusDesc(rsp->_status) << "\r\n";
        for(auto& header : rsp->_headers)
        {
            ss << header.first << ": " << header.second << "\r\n";
        }

        ss << "\r\n";
        ss << rsp->_body.c_str();
        DBG_LOG("resp info: \n%s", ss.str().c_str());

        pc->Send(ss.str().c_str(), ss.str().size());
        DBG_LOG("WriteResponse done");
    }

public:
    HttpServer(uint16_t port, int timeout = 30) : _server(port)
    {
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));  
        _server.EnableInactiveRelease(timeout);     //直接在构造中设置超时
    }

    void SetGetHandle(const string& pattern, Handler handler)   {_get_route.push_back(make_pair(std::regex(pattern),handler));}
    void SetPostHandle(const string& pattern, Handler handler)  {_post_route.push_back(make_pair(std::regex(pattern),handler));}
    void SetPutHandle(const string& pattern, Handler handler)   {_put_route.push_back(make_pair(std::regex(pattern),handler));}
    void SetDeleteHandle(const string& pattern, Handler handler)   {_delete_route.push_back(make_pair(std::regex(pattern),handler));} 
    void SetBaseDir(const string& basedir)  {assert(Util::IsDirectory(basedir)); _basedir = basedir;}
    void SetThreadCount(int count)  {_server.SetThreadCount(count);}

    void Start()    {_server.Start();}
};